package com.jian.异步FileChannle;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.concurrent.Future;

/**
 * @author Jiange
 * @create 2021-09-14-9:48
 */
public class FileChannelDemo4 {
    public static void main(String[] args) throws IOException {
        Path path = Paths.get("C:\\Users\\lenovo\\Desktop\\jain.txt");
        AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ);
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        fileChannel.read(byteBuffer, 0, byteBuffer, new CompletionHandler<Integer, ByteBuffer>() {
            @Override
            public void completed(Integer result, ByteBuffer attachment) {
                System.out.println(result);
                attachment.flip();
                byte[] bytes = new byte[attachment.limit()];
                attachment.get(bytes);
                System.out.println(new String(bytes));
                attachment.clear();
            }

            @Override
            public void failed(Throwable exc, ByteBuffer attachment) {

            }
        });
    }
}
